const { Controller } = require("egg");
class TopicLessonQuestionBankController extends Controller {
    async list() {
        const { lessonId, pageNum, pageSize } = this.ctx.query;
        if (!lessonId) {
            return this.ctx.helper.error("参数异常：缺少lessonId");
        }
        try {
            const res = await this.service.topicLessonQuestionBank.list({
                lessonId,
                pageNum: this.ctx.helper.toInt(pageNum),
                pageSize: this.ctx.helper.toInt(pageSize)
            });
            this.ctx.helper.success(res);
        } catch (error) {
            console.log(error);
            this.ctx.helper.error(`获取题目列表失败：${error.message}`);
        }
    }
    async examList() {
        const { lessonId } = this.ctx.query;
        if (!lessonId) {
            return this.ctx.helper.error("参数异常：缺少lessonId");
        }
        try {
            const res = await this.service.topicLessonQuestionBank.sortList(lessonId);
            this.ctx.helper.success(res);
        } catch (error) {
            console.log(error);
            this.ctx.helper.error(`获取题目列表失败：${error.message}`);
        }

    }

    async create() {
        const { ctx } = this;
        const { topicId, lessonId, title, type, options, correctAnswers } = ctx.request.body;

        if (!topicId || !lessonId ||  !title || !type || !options || !correctAnswers) {
            return this.ctx.helper.error("题目标题、类型、选项、正确答案或topicId不能为空");
        }
        try {
            // const topic = await this.service.topic.id(topicId);
            // if (!topic) {
            //     return this.ctx.helper.error("该专题不存在");
            // }
            // const lesson = await this.service.topicLesson.id(lessonId);
            // if (!lesson) {
            //     return this.ctx.helper.error("该课程不存在");
            // }
            const params = {
                topicId,
                lessonId,
                title,
                type,
                options: options, // 确保选项在保存前已被序列化
                correctAnswers: correctAnswers, // 正确答案同样处理
            };
            const createdQuestion = await ctx.service.topicLessonQuestionBank.create(params);
            this.ctx.helper.success(createdQuestion, "题目创建成功");
        } catch (error) {
            this.ctx.helper.error("创建题目失败：" + error.message);
        }
    }

    async delete() {
        const { id } = this.ctx.request.body;
        if (!id) {
            return this.ctx.helper.error("参数异常：缺少题目ID");
        }
        try {
            const deleted = await this.service.topicLessonQuestionBank.delete(id);
            if (!deleted) {
                return this.ctx.helper.error("题目不存在或删除失败");
            }
            this.ctx.helper.success(deleted, "题目删除成功");
        } catch (error) {
            this.ctx.helper.error("删除题目失败：" + error.message);
        }
    }

    async update() {
        const { id, title, type, options, correctAnswers } = this.ctx.request.body;
        if (!id) {
            return this.ctx.helper.error("参数异常：缺少题目ID");
        }
        try {
            const updateData = {
                ...(title && { title }),
                ...(type && { type }),
                ...(options && { options }),
                ...(correctAnswers && { correctAnswers }),
            };
            const updated = await this.service.topicLessonQuestionBank.update(id, updateData);
            if (!updated) {
                return this.ctx.helper.error("题目不存在或更新失败");
            }
            this.ctx.helper.success(updated, "题目信息更新成功");
        } catch (error) {
            this.ctx.helper.error("更新题目信息失败：" + error.message);
        }
    }



    async createByCsv() {
        const { ctx, service } = this;
        const file = ctx.request.files[0];
        let { lessonId, topicId } = ctx.request.body;
        console.log(file, 'file')
        if (file.filename.indexOf('.csv') === -1) {
            return this.ctx.helper.error("文件格式错误，仅支持CSV文件");
        }

        try {
            const result = await service.excel.readCsvToJson(file.filepath,);
            console.log(result, 'result')
            const arr = [];

            if (result.length > 0) {
                result.forEach(element => {

                    const { A, B, C, D, E, F } = element;
                    let options = {
                        A, B, C, D, E, F
                    }

                    options = Object.entries(options).map(([label, value]) => ({
                        label,
                        value
                    }));

                    options = options.filter((item) => { return item.value })

                    if (element["题干"] && element["题目类型"] && element["正确答案"] && options && options.length) {
                        const params = {
                            lessonId,
                            topicId,
                            title: element["题干"],
                            type: element["题目类型"],
                            correctAnswers: element["正确答案"],
                            options
                        }
                        arr.push(params)

                    }

                });
            }

            if (arr.length) {
                const res2 = await this.ctx.service.topicLessonQuestionBank.createBulk(arr)
                this.ctx.helper.success({
                    success: res2,
                    total: result
                });

            } else {
                return this.ctx.helper.error("未识别到题库，导入失败");

            }


        } catch (err) {
            return this.ctx.helper.error(err, "导入题库失败");
        }
    }
}

module.exports = TopicLessonQuestionBankController;